<?php
/**
 * Dm.php
 * Notes:
 * author: chen
 * DateTime: 2023/2/3 11:06
 * @package Xtsb\Cims\Branch
 */

namespace Xtsb\Cims\Branch;

use Xtsb\Cims\Decorators\TreeDecorator;
use think\facade\Db;

class Dm
{
  //获取id 对应的上级机构label
  public static function label($dmId)
  {
    $dmInfo = Db::name('dm')->field('id,branch_id,title')->where('id', $dmId)->find();
    $branchName = Branch::label($dmInfo['branch_id']);
    return $branchName . ' / ' . $dmInfo['title'];
  }

  /**
   * 获取 $currentDmId 父级id
   * @param $currentDmId
   * @return array
   */
  public static function parentIds($currentDmId)
  {
    $parentIds[] = $currentDmId;//包含当前id
    while ($currentDmId > 0) {
      $currentDmId = Db::name('dm')->where('id', $currentDmId)->value('pid');
      if ($currentDmId) {
        $parentIds[] = $currentDmId;
      }

    }

    return $parentIds;
  }

  /**
   * 排序 部门ID
   * @return array
   */
  public static function sortDmIds(){

    // TODO 是否考虑缓存

    // 获取组织结构
    $list = self::getOrganization();
    $allDmIds = [];

    // 获取有序部门ids（通过组织架构）
    self::sortDmIdByOrganization($list,$allDmIds);

    return is_array($allDmIds)?$allDmIds:[];
  }

  private static function getOrganization(){
    $dms = Db::name('dm')->alias('t1')
      ->field('t1.id,t1.branch_id,t1.pid,CONCAT(t1.title,"（ ",COUNT(t2.id),"人 ）") title,
        CONCAT_WS("_","dm",t1.id) tree_id,"department" icon, NULL style')
      ->leftJoin(USER_TABLE . ' t2', 't2.dm_id=t1.id')
      ->where('t1.cuid', CUID)
      ->group('t1.id')
      ->order('t1.sort,t1.id ASC')->select();

    $dms = TreeDecorator::getTree($dms);
    $dmsList = [];
    foreach ($dms as $dm) {
      $dmsList[$dm['branch_id']][] = $dm;
    }
    unset($dms);

    $branchs = Db::name('branch')->alias('t1')
      ->field('t1.id,pid,t1.title,
      CONCAT_WS("_","branch",t1.id) tree_id,"branch" icon, NULL style')
      ->where('t1.cuid', CUID)
      ->group('t1.id')
      ->order('t1.sort,t1.id ASC')->select()
      ->each(function ($item) use ($dmsList) {
        $childs = [];
        Branch::childs($item['id'], $childs);//获取下级机构

        $staffNum = Db::table(USER_TABLE . ' t')
          ->whereIn('t.branch_id', $childs)
          ->where('t.name', '<>', '管理员')
          ->count();
        $item['title'] = $item['title'] . '（ ' . $staffNum . '人 ）';

        if (isset($dmsList[$item['id']])) {
          $item['dm_list'] = $dmsList[$item['id']];
        }
        return $item;
      });

    return TreeDecorator::getTree($branchs);
  }

  /**
   * 获取结构排序的dmId (排序)
   * @param $list
   * @param $dmIds
   */
  private static function sortDmIdByOrganization($list, &$dmIds = [],$level =0)
  {
    if (!is_array($list)) {
      return;
    }
    $level++;
    foreach ($list as $val) {
      if (!empty($val['icon']) && $val['icon'] == 'department' && !empty($val['id'])) {
        $dmIds[] = $val['id'];
      }
      if (!empty($val['dm_list'])) {
        self::sortDmIdByOrganization($val['dm_list'], $dmIds,$level);
      }
      if (!empty($val['children'])) {
        self::sortDmIdByOrganization($val['children'], $dmIds,$level);
      }
    }
  }
}
